package com.kinyx.examples.services.impl;

import java.io.InputStream;
import java.io.Reader;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.jdbc.BlobProxy;
import org.hibernate.engine.jdbc.ClobProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kinyx.examples.entities.impl.LobsEntity;
import com.kinyx.framework.enums.impl.ErrorCodeX;
import com.kinyx.framework.exception.KRuntimeException;
import com.kinyx.framework.file.KReader;

@Service
public class LobsService {

	private static final String str = "123";
	private static final byte[] bytes = str.getBytes();

	@Autowired
	private SessionFactory sessionFactory;

	public void persist() {
		final Session session = this.sessionFactory.openSession();
		session.beginTransaction();
		final LobsEntity entity = new LobsEntity();
		entity.setLob11(ClobProxy.generateProxy(str));
		entity.setLob12(str.toCharArray());
		entity.setLob13(str);
		entity.setLob21(BlobProxy.generateProxy(bytes));
		entity.setLob22(bytes);
		session.persist(entity);
		System.out.println(entity);
		session.getTransaction().commit();
		session.close();
	}

	public void check() {
		final Session session = this.sessionFactory.openSession();
		session.createQuery("from " + LobsEntity.class.getSimpleName(), LobsEntity.class).getResultList().forEach(entity -> {
			System.out.println(entity);
			try {
				if (!str.equals(this.toString(entity.getLob11().getCharacterStream()))) { throw new KRuntimeException(ErrorCodeX.NeverHappens); }
				if (!str.equals(String.valueOf(entity.getLob12()))) { throw new KRuntimeException(ErrorCodeX.NeverHappens); }
				if (!str.equals(entity.getLob13())) { throw new KRuntimeException(ErrorCodeX.NeverHappens); }
				if (!str.equals(new String(this.toBytes(entity.getLob21().getBinaryStream())))) { throw new KRuntimeException(ErrorCodeX.NeverHappens); }
				if (!str.equals(new String(entity.getLob22()))) { throw new KRuntimeException(ErrorCodeX.NeverHappens); }
			} catch (final Exception e) {
				e.printStackTrace();
			}
		});
		session.close();
	}

	private String toString(final Reader reader) { return KReader.read(reader); }

	private byte[] toBytes(final InputStream is) { return KReader.readBytes(is); }

	public void clear() {
		final Session session = this.sessionFactory.openSession();
		session.beginTransaction();
		session.createQuery("delete from " + LobsEntity.class.getSimpleName()).executeUpdate();
		session.getTransaction().commit();
		session.close();
	}

}
